package top.iflyoung.cim.route.translator;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ScanParams;
import top.iflyoung.cim.common.req.GroupMessageVo;
import top.iflyoung.cim.common.req.P2PMessageVo;
import top.iflyoung.cim.common.util.VerifyUtil;
import top.iflyoung.cim.route.constant.RedisPrefix;
import top.iflyoung.cim.route.util.TimeUtil;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author liguiyang
 * @description
 * @sine 1.8
 * @date 2021/9/622:50
 **/
@Component
public class MessageTranslator {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean parseP2PMessageToRedis(P2PMessageVo messageVo) {
        if (VerifyUtil.isEmpty(messageVo)) {
            throw new NullPointerException("存入redis的消息为空");
        }
        String p2pKey = getP2PKeyAtToday();
        return redisTemplate.opsForSet().add(p2pKey, JSON.toJSONString(messageVo)) > 0;
    }

    public Set<P2PMessageVo> parseP2PMessageFromRedisAtToday() {
        return parseP2PMessageFromRedis(getP2PKeyAtToday());
    }

    public Set<P2PMessageVo> parseP2PMessageFromRedisAtYesterday() {
        return parseP2PMessageFromRedis(getP2PKeyAtYesterday());
    }

    private Set<P2PMessageVo> parseP2PMessageFromRedis(String p2pKey) {
        Set<P2PMessageVo> result = new HashSet<>();
        if (redisTemplate.hasKey(p2pKey)) {
            Set<String> p2pMessages = redisTemplate.opsForSet().members(p2pKey);
            for (String msg : p2pMessages) {
                result.add(JSON.parseObject(msg, P2PMessageVo.class));
            }
        }
        return result;
    }

    public boolean parseGroupMessageToRedis(GroupMessageVo groupMessage) {
        if (VerifyUtil.isEmpty(groupMessage)) {
            throw new NullPointerException("存入redis的消息为空");
        }
        String groupKey = getGroupKeyAtToday(groupMessage.getGroupId());
        return redisTemplate.opsForSet().add(groupKey, JSON.toJSONString(groupMessage)) > 0;
    }

    public Set<GroupMessageVo> parseGroupFromRedisAtToday(Long groupId) {
        return parseGroupFromRedis(groupId, getGroupKeyAtToday(groupId));
    }

    public Set<GroupMessageVo> parseGroupFromRedisAtYesterday() {
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(RedisPrefix.GROUP_PREFIX);
        keyBuilder.append(TimeUtil.getYesterday());
        keyBuilder.append(RedisPrefix.SPLIT);
        keyBuilder.append("*");
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        ScanOptions options = ScanOptions.scanOptions()
                .match(keyBuilder.toString())
                .build();
        Cursor<byte[]> scan = connection.scan(options);
        Set<String> result = new HashSet<>();
        while (scan.hasNext()) {
            byte[] next = scan.next();
            String key = new String(next, StandardCharsets.UTF_8);
            result.addAll(redisTemplate.opsForSet().members(key));
        }
        Set<GroupMessageVo> voSet = new HashSet<>();
        if (!VerifyUtil.isEmpty(voSet)) {
            for (String json : result) {
                voSet.add(JSON.parseObject(json, GroupMessageVo.class));
            }
        }
        return voSet;
    }

    public Set<GroupMessageVo> parseGroupFromRedisAtYesterday(Long groupId) {
        return parseGroupFromRedis(groupId, getGroupKeyAtYesterday(groupId));
    }

    private Set<GroupMessageVo> parseGroupFromRedis(Long groupId, String groupKey) {
        Set<GroupMessageVo> messageSet = new HashSet<>();
        if (redisTemplate.hasKey(groupKey)) {
            Set<String> groupMessages = redisTemplate.opsForSet().members(groupKey);
            for (String msg : groupMessages) {
                messageSet.add(JSON.parseObject(msg, GroupMessageVo.class));
            }
        }
        return messageSet;
    }

    /**
     * 使用Set,存储json
     *
     * @return
     */
    public static String getP2PKeyAtYesterday() {
        return getP2PKey(TimeUtil.getYesterday());
    }

    /**
     * @param groupId
     * @return
     */
    public static String getGroupKeyAtYesterday(Long groupId) {
        return getGroupKey(groupId, TimeUtil.getYesterday());
    }

    /**
     * 使用Set,存储json
     *
     * @return
     */
    public static String getP2PKeyAtToday() {
        return getP2PKey(TimeUtil.getToday());
    }

    /**
     * @param groupId
     * @return
     */
    public static String getGroupKeyAtToday(Long groupId) {
        return getGroupKey(groupId, TimeUtil.getToday());
    }

    /**
     * 使用Set,存储json
     *
     * @return
     */
    private static String getP2PKey(String dateString) {
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(RedisPrefix.P2P_CHAT);
        keyBuilder.append(dateString);
        return keyBuilder.toString();
    }

    /**
     * @param groupId
     * @return
     */
    private static String getGroupKey(Long groupId, String dateString) {
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(RedisPrefix.GROUP_PREFIX);
        keyBuilder.append(dateString);
        keyBuilder.append(RedisPrefix.SPLIT);
        keyBuilder.append(groupId);
        return keyBuilder.toString();
    }
}
